package cn.xiangxu.telecom.login.controller;

import java.io.Serializable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.xiangxu.telecom.login.entity.Admin;
import cn.xiangxu.telecom.login.service.ApplicationException;
import cn.xiangxu.telecom.login.service.LoginSerice;

@Controller
public class LoginController implements Serializable {
	@Resource(name="loginService")
	private LoginSerice ls;
	
	@RequestMapping("/toLogin.do")
	public String toLogin() {
		System.out.println("去往登录页面...");
		return "login";
	}
	
	@RequestMapping("/toIndex.do")
	public String toIndex(HttpSession session, HttpServletRequest req) {
		System.out.println("如果用户信息正确就执行重定向到主页的过程...");
//		 读取账号和密码
		String adminCode = req.getParameter("adminCode");
		String password = req.getParameter("password");
		System.out.println("adminCode -->> " + adminCode);
		System.out.println("password -->> " + password);
		
		/* 利用spring框架来处理异常后，就不需要三少来进行捕获异常啦
		try {
			Admin admin = ls.checkLogin(adminCode, password);
		} catch(Exception e) {
			e.printStackTrace(); //记录日志
			if(e instanceof ApplicationException) { //应用异常：能够处理俺就处理啦
				req.setAttribute("failed", e.getMessage());
				return "login"; // 应用异常时转发到登录页面
			}
			return "error"; // 运行异常：俺不能处理就重定向到一个指定的错误页面
		}
		*/
		Admin admin = ls.checkLogin(adminCode, password);
		session.setAttribute("admin", admin); // 将从数据库中读取到的用户信息放到session中去
		
//		登录成功：重定向到主页面
		return "redirect:index.do";
	}
	
	@RequestMapping("/index.do")
	public String index() {
		System.out.println("转发到主页...");
		return "index";
	}
	
	@ExceptionHandler
	public String executeError(Exception e, HttpServletRequest request) {
		if(e instanceof ApplicationException) {
			request.setAttribute("failed", e.getMessage());
			return "login";
		}
		return "error";
	}
}
